<?php
namespace Model;



use Model\Factory\TableGatewayFactory;

class Menu extends AbstractModel
{
    public $id;
    public $code;
    public $name;
    public $description;
    public $created_date;
    public $created_by;
    public $active;


    public function getMenuAsKendoDataSource()
    {
        $rows = $this->getAllMenuItem(1);
        return $this->getTreeKendoDatasource($rows);
    }

    private function getTreeKendoDatasource($rows){
        $right = array();
        $result = array();

        foreach ($rows as $itemObj) {
            $item = (array)$itemObj;
            $item["text"] = $item["label"];
            $item["my_url"] = $item["url"];
            unset($item["url"]);

            if(count($right)>0){
                while ($right[count($right)-1]['rgt']<$item['rgt']) {
                    array_pop($right);
                }
            }
            if($item['lft'] < $item['rgt'] -1){

                $item["items"] = array();
            }
            if(count($right)>0){
                $latestHasChildren = &$this->findLatestHasChildren($result[(count($result)-1)], $right[count($right)-1]);

                $latestHasChildren["items"][] =  $item;

            }else{
                call_user_func_array("array_push", array(&$result,&$item));
            }

            call_user_func_array("array_push", array(&$right,&$item));

        }
        return $result;
    }

    private function &findLatestHasChildren(&$arr, $sample){

        if(array_key_exists("items",$arr)){
            if(count($arr["items"]) == 0 || !array_key_exists("items",$arr["items"][count($arr["items"]) -1]) ){
                return $arr;
            }elseif(array_key_exists("items",$arr["items"][count($arr["items"]) -1])
                && $arr["items"][count($arr["items"]) -1]["rgt"] < $sample["rgt"]){
                return $arr;
            }
            else {
                return $this->findLatestHasChildren($arr["items"][count($arr["items"]) -1],$sample);
            }
        }
        else{
            return $arr;
        }
    }

    public function getAllMenuItem($active = -1){
        $menuItemTable = TableGatewayFactory::getMenuItemTable();
        $select = $menuItemTable->getDbSqlSelect()
        ->where(array('menu_id'=>$this->id));
        if($active >= 0){
            $select->where(array('active'=>$active));
        }
        $select->order(array('lft'));
        $rsi = $menuItemTable->getTableGateway()->selectWith($select);
        $resultArr = array();
        foreach ($rsi as $aMenuItem) {
            array_push($resultArr, $aMenuItem);
        }
        return $resultArr;
    }


}
